import Title from "ant-design-vue/es/typography/Title";
import * as XLSX from "xlsx";

const stringTobuff = (str) => {
  let buf = new ArrayBuffer(str.length);
  let view = new Uint8Array(buf);
  for (let i = 0; i != str.length; ++i) view[i] = str.charCodeAt(i) & 0xff;
  return buf;
};

const getXlsl = (data) => {
  return new Promise((resolve) => {
    let WorkSheet = XLSX.utils.aoa_to_sheet(data);
    let new_workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(new_workbook, WorkSheet);
    // const buff = XLSX.write(new_workbook, {
    //   bookType: "xlsx", // 要生成的文件类型
    //   bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
    //   type: "binary",
    // });
    const buff = XLSX.write(new_workbook, {
      bookType: "xlsx", // 要生成的文件类型
      bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
      type: "binary",
    });
    resolve(buff);
  });
};

export const downloadXlsx = async (id, data, columns, name) => {
  columns = columns.filter(
    (a) => a.key !== ("operate" || "caozuo" || "cz") && a.key !== "serial"
  );
  const cm = columns.map((a) => a.title);
  console.log(columns, "dfdsfd");
  let arr = [cm];
  const res = data.map((a, i) => {
    let o = [];
    columns.forEach((c) => {
      if (c.render) {
        o = o.concat(c.render(a));
      } else if (c.slotName) {
        const cs = `.${c.slotName}-${id}`;
        const el = document.querySelectorAll(cs);
        o = o.concat(el[i].innerText);
      } else {
        o = o.concat(a[c.key] || "");
      }
    });
    return o;
  });
  arr = arr.concat(res);
  const buff = await getXlsl(arr);
  const blob = new Blob([stringTobuff(buff)]);
  const href = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = href;
  a.download = `${name}.xlsx`;
  document.body.appendChild(a);
  a.click();
  setTimeout(() => {
    URL.revokeObjectURL(blob);
    document.body.removeChild(a);
  }, 100);
};
